import { ShelfPaper } from '@/api/Shelf';
import TestPaperDetail from '@/components/resourceLibraryComp/TestPaperDetail';
import { useReactive } from 'ahooks';
import { App, Button, Drawer, Modal } from 'antd';
import { useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { LeftClassTree } from '../../../LeftClassTree';
import { ShelfAIRef, ShelfUpperModalContent, ShelfUpperRef } from '../../../UpperContent';
import { CreateFromPaper } from '../AddEdit/createFromPaper';
type RecordType = ShelfPaper;

interface ListPorps {
  // 新增编辑事件
  onAddEdit?(value?: { classId?: string; parClassId?: string }): void;
  // 打开弹窗事件
  onDetail?(): Promise<boolean>;
  // 删除事件
  onDelete?(): Promise<boolean>;
}

export function List({ onAddEdit }: ListPorps) {
  const [columns] = useState<YmColumnsType<RecordType>>([
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: 'num',
      width: 200,
      render() {
        return 1;
      },
    },
    {
      key: '_operate',
      title: '操作',
      width: 140,
    },
  ]);
  const [extraParams, setExtraParams] = useState<{ classId?: string; parClassId?: string }>({
    classId: undefined,
    parClassId: undefined,
  });
  const upperRef = useRef<ShelfUpperRef>(null);
  const AIRef = useRef<ShelfAIRef>(null);
  const upperExtram = useReactive<{ guid?: string; aiLearnClassification?: number }>({
    guid: undefined,
    aiLearnClassification: 0,
  });
  const { modal } = App.useApp();
  const detailsPorps = useReactive<{ props: { coursewareId: string } }>({ props: { coursewareId: '' } });
  const [secPaper, openSecPaper] = useState<number>();
  const [reFresh, setRefresh] = useState<number>();
  const reFreshTreeAndTable = () => {
    setExtraParams((v) => ({ ...v }));
    setRefresh(Math.random());
  };

  return (
    <div className="safe_boss_pagelr">
      <div className="safe_boss_page_left">
        <LeftClassTree
          type="4"
          value={extraParams.classId}
          onSelect={(classId, parClassId) => {
            setExtraParams((p) => ({ ...p, classId, parClassId }));
          }}
          refreshDeps={[reFresh]}
        ></LeftClassTree>
      </div>
      <div className="safe_boss_page_right">
        <YmTable
          searchForm={{
            formItems: [
              {
                label: '名称',
                name: 'name',
                valueType: {
                  type: 'input',
                },
              },
            ],
          }}
          toolBar={{
            prefixNode: (
              <>
                <Button
                  type="primary"
                  onClick={() => {
                    console.log(extraParams, '----');
                    onAddEdit?.(extraParams);
                  }}
                >
                  新增试卷
                </Button>
                <Button
                  type="primary"
                  onClick={() => {
                    openSecPaper(Math.random());
                  }}
                >
                  选择试卷
                </Button>
              </>
            ),
          }}
          columns={columns}
          request={async ({ page }, form) => {
            const { current = 0, pageSize = 10 } = page ?? {};
            const data = await ShelfPaper.unShelfList(current, pageSize, { ...form, classId: extraParams.classId });
            return data;
          }}
          requestOptions={{
            reFreshDep: [extraParams],
            defaultPageSize: 20,
          }}
          rowKey="guid"
          operate={[
            {
              text: '详情',
              key: 'detail',
              onClick(record) {
                detailsPorps.props = {
                  coursewareId: record.guid,
                };
              },
            },
            {
              text: '删除',
              key: 'delete',
              onClick(record) {
                modal.confirm({
                  title: '提示',
                  content: `确定要删除【${record.name}】吗`,
                  async onOk() {
                    await ShelfPaper.delete(record.guid);
                    reFreshTreeAndTable();
                  },
                });
              },
            },
            {
              text: '上架',
              key: 'listing',
              hidden(record) {
                return record.aiLearnClassification == 1;
              },
              onClick(record) {
                upperExtram.guid = record.guid;
                upperExtram.aiLearnClassification = record.aiLearnClassification;
              },
            },
          ]}
        ></YmTable>
      </div>
      <Modal
        title="上架"
        width={1120}
        open={Boolean(upperExtram.guid)}
        onCancel={() => (upperExtram.guid = undefined)}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          const result = await upperRef.current?.submit();
          await ShelfPaper.shelf.upper({ ...upperExtram, ...result });
          upperExtram.guid = undefined;
          upperExtram.aiLearnClassification = undefined;
          reFreshTreeAndTable();
        }}
      >
        <div style={{ maxHeight: '450px', overflowY: 'auto' }}>
          <ShelfUpperModalContent ref={upperRef}></ShelfUpperModalContent>
        </div>
      </Modal>
      {/* 暂时注释 这期先不做ai试卷上架 需要了再放出来就好了<Modal
        title="上架"
        width={upperExtram.aiLearnClassification != 1 ? '900px' : '400px'}
        open={Boolean(upperExtram.guid)}
        onCancel={() => (upperExtram.guid = undefined)}
        centered
        destroyOnClose
        maskClosable={false}
        onOk={async () => {
          const result =
            upperExtram.aiLearnClassification != 1 ? await upperRef.current?.submit() : await AIRef.current?.submit();
          await ShelfPaper.shelf.upper({ ...upperExtram, ...result });
          upperExtram.guid = undefined;
          upperExtram.aiLearnClassification = undefined;
          reFreshTreeAndTable();
        }}
      >
        <div style={{ maxHeight: '450px', overflowY: 'auto' }}>
          {upperExtram.aiLearnClassification != 1 ? (
            <ShelfUpperModalContent ref={upperRef}></ShelfUpperModalContent>
          ) : (
            <ShelfAIModalContent ref={AIRef}></ShelfAIModalContent>
          )}
        </div>
      </Modal> */}
      <Drawer
        width={800}
        open={Boolean(detailsPorps.props.coursewareId)}
        title="详情"
        bodyStyle={{
          background: '#eff2f5',
          padding: '12px',
        }}
        onClose={() => {
          detailsPorps.props.coursewareId = '';
        }}
        destroyOnClose
      >
        <TestPaperDetail {...detailsPorps.props} />
      </Drawer>
      <CreateFromPaper
        openDep={secPaper}
        onSuccess={() => {
          setExtraParams((v) => ({ ...v }));
          reFreshTreeAndTable();
        }}
      ></CreateFromPaper>
    </div>
  );
}
